package com.srlg.boot.statemachine.service;

import com.srlg.boot.statemachine.config.OrderEvents;
import com.srlg.boot.statemachine.config.OrderStatus;
import com.srlg.boot.statemachine.domain.Order;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

/**
 * @desc:
 * @author: srlg li
 * @date: 2025/6/29 下午10:05
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderProcessor {

    final StateMachine<OrderStatus, OrderEvents> orderStateMachine;


    final StateMachinePersister<OrderStatus, OrderEvents, Order> persister;

    public Boolean process(Order order, OrderEvents events) {
        Message<OrderEvents> msg = MessageBuilder.withPayload(events)
            .setHeader("order", order).build();

        return sendEvent(msg);
    }

    @SneakyThrows
    private boolean sendEvent(Message<OrderEvents> msg) {
        Order order = (Order) msg.getHeaders().get("order");
        persister.restore(orderStateMachine, order);

        return orderStateMachine.sendEvent(msg);
    }


}
